import { crtChannel } from "./crtChannel";
import { crtChannelWeb } from "./crtChannelWeb";
import crtkc from "./crtkc";

/**如花的奇葩事  包名:com.jym.rhdqps.vivominigame */
export class crtChannelVivo extends crtChannelWeb {
    channelObj: any = (window as any).qg;
    paraMap: Map<String, string> = new Map([
        ['bannerId', 'a2d0dd66559a4828b9bdd330e5f12387'],
        ['customInsertAd', '6d9cd5353b7f4216a22b247976e5ca74'],
        ['videoId', 'd4e3ce6559244d69bbe8d13225ea3fae'],
        // ['htId', '1951116'],
        ['ctrlId', '676cc956ac07a817fa283c4e'],
        // ['gid', '674546ecc5b6582182fb7e6a'],
    ]);

    ruanzhu: string = '著作权人: 南京天豆互动网络科技有限公司\n登记号:2022SR0554085';
    /** getSystemInfoSync */
    getSysInfo(): any {
        if (!this.sysInfo) {
            this.sysInfo = this.channelObj.getSystemInfoSync();
        }
        return this.sysInfo;
    }

    exit(): void {
        this.channelObj.exitApplication();
    }

    isBuyUser: boolean = false;
    init(){
        const me = this;
        let query = this.channelObj.getLaunchOptionsSync().query;
        console.error("启动参数: ", query);
        if (query && query.path && query.path.indexOf("key=fromid") >= 0) {
            console.error("买量用户: ");
            this.isBuyUser = true;
        }
        const ctrlId = this.getPara('ctrlId');
        if (ctrlId) {
            let reqData = null;
            if (this.isBuyUser) {
                reqData = {
                    'id': ctrlId,
                    'fromid': 1,
                }
            } else {
                reqData = {
                    'id': ctrlId
                }
            }
            crtChannel.jpost('https://ga.gametdd.com/adCtrl/agd/conf', reqData, (err, re) => {
                if (err) {
                    console.error("错误: ", err);
                    return;
                }
                if ('' + re.code !== '0') {
                    console.error('返回值错误:' + JSON.stringify(re));
                    return;
                }
                me.ctrl = re.data;
                console.error('====>返回', me.ctrl);
            });
        }
    }



    showVideo(succ) {
        const id = this.getPara('videoId');
        if (!id) {
            return;
        }
        
        console.error('====>showVideo');
        try {
            cc.game.pause();
            var videoAd = window['qg'].createRewardedVideoAd({
                adUnitId: id
            });
            videoAd.load();
            videoAd.onLoad(() => {
                videoAd.show();
            });
            videoAd.onError(err => {
                console.error('视频Error:' + JSON.stringify(err));
                crtChannel.toast('暂无广告');
                cc.game.resume();
            });
            videoAd.onClose((res) => {
                cc.game.resume();
                if (res == undefined) {
                    succ();
                } else {
                    // 用户点击了【关闭广告】按钮
                    if (res.isEnded) {
                        //看完广告,给奖励
                        succ();
                    }
                }
            });
        } catch (e) {
            console.error('videoERR', e);
            cc.game.resume();
        }
    }


    /** 分渠道的广告特定动作，actId区分哪个动作,para为执行动作需要的对象
     * 1:二级页面弹出插屏并覆盖按钮
     * 2:连点宝箱弹出底部banner
     * 3:主页原生插屏弹出
     * 4:每两关在游戏过程中弹出原生插屏.
     *
     */
    passPart: number = 1;
    doAction(actId: number, para: any) {
        console.log("doaction:", actId, para);
        let watchAd = ()=>{
            this.showVideo(()=>{

            });
        }
        if(para && para[0] == 'vivo'){
            console.error("vivo策略: ", actId);
            if(actId == 1){
                let isOpen = this.getCtrl('p1');
                if(isOpen){
                    let delayTime = this.getCtrl('p2') * 1000;
                    setTimeout(()=>{
                        let style = {
                            top: this.getSysInfo().windowHeight / 2 + 100
                        }
                        this.showCustomAd(false, false, style);
                    }, delayTime);
                }
            }else if(actId == 2){
                let isOpen = this.getCtrl('p3');
                if(isOpen){
                    this.showBanner();
                }
            }else if(actId == 3){//主页弹出原生插屏
                let isOpen = this.getCtrl('p4');
                if(isOpen){
                    let delayTime = this.getCtrl('p5') * 1000;
                    let style = {
                        top: this.getSysInfo().windowHeight / 2 + 100
                    }
                    setTimeout(()=>{
                        this.showCustomAd(false, false, style);
                    }, delayTime);
                }
            }else if(actId == 4){
                let isOpen = this.getCtrl('p6');
                if(isOpen){
                    this.passPart++;
                    if(this.passPart > 0 && this.passPart % 2 == 0){
                        let delayTime = 1 + Math.random() * 3;
                        setTimeout(()=>{
                            this.showCustomAd(false);
                        }, delayTime * 1000);
                    }
                }
            }
        }
    }


    bannerAd: any = null;
    /**下次展示banner时间 */
    nextBannerTime: number = 0;
    showBanner(isForce?: boolean, styleFn?: any, where?: string): void {
        const id = this.getPara('bannerId');
        if (!id) {
            return;
        }
        if (Date.now() < this.nextBannerTime) {
            crtkc.log('间隔时间未到');
            return;
        }
        crtkc.log('showBanner', id);
        this.nextBannerTime = Date.now() + 3000;
        this.bannerAd = this.channelObj.createBannerAd({
            posId: id,
        });
        this.bannerAd.onError(err => {
            crtkc.log('banner广告加载失败' + JSON.stringify(err));
            styleFn && styleFn(0);
        });

        this.bannerAd.show().then(() => {
            crtkc.log('banner广告展示完成');
        }).catch((err) => {
            crtkc.log('banner广告展示失败' + JSON.stringify(err));
            styleFn && styleFn(0);
        });

        this.bannerAd.onClose(err => {
            styleFn && styleFn(1);
            crtkc.log('banner广告关闭' + JSON.stringify(err));
        });

    }

    closeBanner(): void {
        if (this.bannerAd) {
            this.bannerAd.hide();
        }
    }


    /** 上一次custom展示时间 */
    private lastCustomShowTime: number = 0;
    /** customAd展示时间间隔，单位毫秒 */
    private customGapSec: number = 5000;

    private customAdMap = {};
    showCustomAd(isBanner: boolean, isForce?: boolean, style?: any): void {
        const id = this.getPara('customInsertAd');
        if (!id) {
            return;
        }
        if (Date.now() - this.lastCustomShowTime < this.customGapSec) {
            crtkc.log('custom广告间隔未到', this.customGapSec);
            return;
        }
        this.lastCustomShowTime = Date.now();
        const height = this.getSysInfo().windowHeight / 2 - 300;
        crtkc.log('showCustomAd', id, isBanner, height);
        const conf = {
            'posId': id,
            'style': {
                'top': height,
            }
        }
        if (style) {
            conf['style'] = style;
        }
        crtkc.log('原生模板将创建', id);
        this.customAdMap[id] = this.channelObj.createCustomAd(conf);
        this.customAdMap[id].offError();
        this.customAdMap[id].onError(err => {
            crtkc.log("原生模板广告加载失败" + JSON.stringify(err));
        });
        this.customAdMap[id].offClose();
        this.customAdMap[id].onClose(err => {
            crtkc.log("原生模板广告关闭" + JSON.stringify(err));
        });

        this.customAdMap[id].show().then(() => {
            crtkc.log('原生模板广告展示完成');
        }).catch((err) => {
            crtkc.log('原生模板广告展示失败' + JSON.stringify(err));
        });

    }
    closeCustomAd(isBanner?: boolean): void {
        const id = this.getPara('customInsertAd');
        if (!id) {
            return;
        }
        if (this.customAdMap[id]) {
            this.customAdMap[id].hide();
        }
    }
}